package com.ccc.boot.system.controller;

import com.ccc.boot.base.BaseController;
import com.ccc.boot.constant.CommonConstant;
import com.ccc.boot.exception.BusinessException;
import com.ccc.boot.pojo.MenuTree;
import com.ccc.boot.response.ResponseCode;
import com.ccc.boot.response.ResponseResult;
import com.ccc.boot.system.pojo.AuthMenuTree;
import com.ccc.boot.system.pojo.AuthMenuVO;
import com.ccc.boot.system.pojo.SysMenuTree;
import com.ccc.boot.system.entity.SysMenu;
import com.ccc.boot.system.service.SysMenuService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * 菜单
 *
 * @author superC
 * @version 0.1.0
 * @date 2022/3/30
 */

@RestController
@RequestMapping(CommonConstant.SYS_URI_PREFIX + "/menu")
public class SysMenuController extends BaseController<SysMenu, SysMenuService> {

    /**
     * 获取菜单tree（菜单管理）
     *
     * @return {@link ResponseResult}
     * @date 2022/3/30 16:19
     * @author superC
     */
    @GetMapping("/getAllMenuTree")
    public ResponseResult getAllMenuTree() {
        List<SysMenuTree> tree = service.getAllMenuTree();
        return ResponseResult.success("获取菜单数据成功", tree);
    }

    /**
     * 获取当前角色已授权的菜单集
     *
     * @date 2022/4/8 13:23
     * @param roleId
     * @return {@link ResponseResult}
     * @author superC
     */
    @GetMapping("/getAuthMenuTree/{roleId}")
    public ResponseResult getAuthMenuTree(@PathVariable Long roleId) {
        try {
            AuthMenuVO data = service.getAuthMenuTree(roleId);
            return ResponseResult.success("获取菜单数据成功", data);
        } catch (Exception e) {
            logger.error("【捕获异常-获取数据操作】\r\n异常记录：", e);
            throw new BusinessException(ResponseCode.DATA_GET_ERROR);
        }
    }

    /**
     * 删除所选节点及其子节点
     *
     * @param menuTree
     * @return {@link ResponseResult}
     * @date 2022/3/30 16:19
     * @author superC
     */
    @Transactional(rollbackFor = Exception.class)
    @PostMapping("/deleteNodes")
    public ResponseResult deleteNodes(@RequestBody MenuTree menuTree) {
        try {
            service.deleteNodes(menuTree);
        } catch (Exception e) {
            logger.error("【捕获异常-删除操作】\r\n异常记录：", e);
            //手工回滚异常
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new BusinessException(ResponseCode.DATA_DELETE_FAILURE);
        }
        return ResponseResult.success(ResponseCode.DATA_DELETE_SUCCESS);
    }
}